package com.cetc.expt;
import com.cetc.expt.utils.ProxyUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;

/**
 * @author louzhuangxi
 * @Classname JdkDynamicProxy
 * @Description JDK动态代理 实现代码日志功能增强
 * @Date 2022/12/15 20:04
 */
public class JdkDynamicProxy {
    public static void main(String[] args) {
        IUserService userService = new UserServiceImpl();
        IUserService proxy = (IUserService) JdkProxyFactory.getInstance(userService);
        System.out.println("代理对象:" + proxy.getClass());
        //执行方法
        proxy.select();
        proxy.update();
        ProxyUtils.generateClassFile(proxy.getClass(),"UserServiceProxy");
    }
}

/**
 * JDK动态代理工厂
 */
class JdkProxyFactory {
    /**
     * 获取实例
     *
     * @param target 被代理对象
     * @return 代理对象
     */
    public static Object getInstance(Object target) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new LogHandler(target));
    }
}

/**
 * 真实主题角色
 */
class LogHandler implements InvocationHandler {
    private final Object target;

    public LogHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object invoke = method.invoke(target, args);
        after();
        return invoke;
    }

    private void before() {
        System.out.println("before");
    }

    private void after() {
        System.out.println("after");
    }
}

interface IUserService {
    void select();

    void update();
}

class UserServiceImpl implements IUserService {
    @Override
    public void select() {
        System.out.println("查询 select");
    }

    @Override
    public void update() {
        System.out.println("更新 update");
    }
}